package com.example.qxfw.nyqx.controller;

import com.alibaba.excel.EasyExcel;
import com.example.qxfw.mongodb.hy.entity.HyImageFile;
import com.example.qxfw.mongodb.hy.service.HyImageFileService;
import com.example.qxfw.nyqx.dto.SumRainAndSunAndTempDto;
import com.example.qxfw.nyqx.vo.GrowdateListVo;
import com.example.qxfw.nyqx.vo.SumDataVo;
import com.example.qxfw.nyqx.vo.SumRainAndSunAndTempListVo;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.ny.*;
import com.example.qxfw.common.entity.qx.MsgMediumSmallScale;
import com.example.qxfw.common.entity.xt.AgriMoniInfo;
import com.example.qxfw.nyqx.dto.CltjDto;
import com.example.qxfw.nyqx.service.*;
import com.example.qxfw.common.util.StringUtil;
import com.example.qxfw.config.excel.CustomCellWriteWeightConfig;
import com.example.qxfw.rcyw.service.AgriMoniInfoService;
import com.example.qxfw.rcyw.service.StationInfoService;
import com.example.qxfw.ybzz.service.MsgMediumSmallScaleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@ApiIgnore
@Api(tags = "农业气象-农业信息服务站")
@RestController
@CrossOrigin
@RequestMapping("/AgriculturalServiceInformationStationController")
public class AgriculturalServiceInformationStationController {

    @Value("${filePath.excelPath}")
    private String excelPath;

    @Autowired
    private StationInfoService stationInfoService;

    @Autowired
    private MsgMediumSmallScaleService msgMediumSmallScaleService;

    @Autowired
    private CropyieldHistoryService cropyieldHistoryService;

    @Autowired
    private CropGrowdateIndexlibService cropGrowdateIndexlibService;

    @Autowired
    private CropyieldFcstService cropyieldFcstService;

    @Autowired
    private CltjService cltjService;

    @Autowired
    private AgriMoniInfoService agriMoniInfoService;

    @Autowired
    private AgriculturalServiceInformationStationService agriculturalServiceInformationStationService;

    @Autowired
    private CropGrowdateFcstService growdateFcstService;

    @Autowired
    private CropGrowdateHistoryService cropGrowdateHistoryService;

    @Autowired
    private CropGrowdateIndexlibService growdateIndexlibService;

    @Autowired
    private FyqtjService fyqtjService;

    @Autowired
    private HyImageFileService imageFileService;

    @ApiOperation("农业气象-农业信息服务站-按条件查询农服站点")
    @RequestMapping("/getStationInfoByParam")
    public SysResult getStationInfoByParam(String stationId, String stationName, String county) {
        List<StationInfo> stationInfos = agriculturalServiceInformationStationService.selectAgriculturalServiceInformationStation(stationId, stationName, county);
        return SysResult.common(stationInfos);
    }

    @ApiOperation("农业气象-农业信息服务站-根据id获取图片")
    @GetMapping("/getStationImgById")
    public ResponseEntity<byte[]> getDopplerById(String id, String name) {
        HyImageFile imgFile = imageFileService.getById(id);
        byte[] data = imgFile.getData();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG); // 设置为图片的MIME类型
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename(name + ".jpg").build());
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }

    @ApiOperation("农业气象-农业信息服务站-站点编号")
    @RequestMapping("/getStationInfoStationId")
    public SysResult getStationInfoStationId() {
        List<String> list = agriculturalServiceInformationStationService.selectDistinctStationId();
        return SysResult.common(list);
    }

    @ApiOperation("农业气象-农业信息服务站-站点名称")
    @RequestMapping("/getStationInfoStationName")
    public SysResult getStationInfoStationName() {
        List<String> list = agriculturalServiceInformationStationService.selectDistinctStationName();
        return SysResult.common(list);
    }

    @ApiOperation("农业气象-农业信息服务站-所属县市")
    @RequestMapping("/getStationInfoCounty")
    public SysResult getStationInfoCounty() {
        List<String> list = agriculturalServiceInformationStationService.selectDistinctCounty();
        return SysResult.common(list);
    }

    @ApiOperation("农业气象-农业信息服务站-农事站要素统计图")
    @RequestMapping("/getStatisticalChartOfAgriculturalStationElements")
    public SysResult getStatisticalChartOfAgriculturalStationElements(String stationId, String column, String startDate, String startTime, String endDate, String endTime) {
        String start = startDate + " " + startTime + ":00:00";
        String end = endDate + " " + endTime + ":00:00";
        String type = StringUtil.chineseToEnglish(column);
        List<MsgMediumSmallScale> statisticalChartOfAgriculturalStationElements = agriculturalServiceInformationStationService.getStatisticalChartOfAgriculturalStationElements(stationId, type, Timestamp.valueOf(start), Timestamp.valueOf(end));
        return SysResult.common(statisticalChartOfAgriculturalStationElements);
    }

    @ApiOperation("农业气象-农业信息服务站-农事站要素统计图-导出excel")
    @RequestMapping("/exportAgriculturalStationElementsData")
    public String exportAgriculturalStationElementsData(String excelName, String stationId, String column, String startDate, String startTime, String endDate, String endTime) {
        String start = startDate + " " + startTime + ":00:00";
        String end = endDate + " " + endTime + ":00:00";
        String type = StringUtil.chineseToEnglish(column);
        List<MsgMediumSmallScale> statisticalChartOfAgriculturalStationElements = agriculturalServiceInformationStationService.getStatisticalChartOfAgriculturalStationElements(stationId, type, Timestamp.valueOf(start), Timestamp.valueOf(end));
        // 创建一个新的Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Sheet1");
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        CellStyle headerCellStyle = workbook.createCellStyle();
        headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 创建标题列
        String[] columns = {"日期", column};
        for (int i = 0; i < columns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columns[i]);
            cell.setCellStyle(headerCellStyle);
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        int rowNum = 1;
        for (final MsgMediumSmallScale msgMediumSmallScale : statisticalChartOfAgriculturalStationElements) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(dateFormat.format(msgMediumSmallScale.getObservtime()));
            row.createCell(1).setCellValue(String.valueOf(StringUtil.getData(msgMediumSmallScale, column)));
        }
        excelName = excelName.endsWith(".txt") ? excelName : excelName + ".xlsx";
        // 将工作簿保存到文件
        try (FileOutputStream fileOut = new FileOutputStream(excelPath + "/" + excelName)) {
            workbook.write(fileOut);
            System.out.println("Excel文件已创建成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭工作簿
        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "192.168.0.15:81/" + excelName;
    }

    @ApiOperation("农业气象-农业信息服务站-作物发育期查询统计-实况查询")
    @RequestMapping("/queryRealSituationQueryOfCropDevelopmentPeriod")
    public SysResult queryRealSituationQueryOfCropDevelopmentPeriod(String stationId, Integer year, String cropName, String type){
        List<CropGrowdateHistory> cropGrowdateHistories = agriculturalServiceInformationStationService.queryRealSituationQueryOfCropDevelopmentPeriod(stationId, year, cropName, type);
        return SysResult.common(cropGrowdateHistories);
    }

    @ApiOperation("根据经度、纬度查询站点信息")
    @GetMapping("/getStationInfo")
    public SysResult getStationInfo(String jd, String wd) {
        List<StationInfo> list = stationInfoService.listByParam1(jd, wd);
        return SysResult.common(list);
    }


    @ApiOperation("农事站要素查询")
    @GetMapping("/getStationElement")
    public SysResult getStationElement(String time1, String time2, String stationId, String element) {
        List<MsgMediumSmallScale> list = msgMediumSmallScaleService.getList26(time1, time2, stationId, element);
        return SysResult.success(list);
    }

    @ApiOperation("获取作物名称")
    @GetMapping("/getCropName")
    public SysResult getCropName() {
        List<String> cropName = cropGrowdateIndexlibService.getCropName();
        return SysResult.success(cropName);
    }

    @ApiOperation("获取作物品种")
    @GetMapping("getCropType")
    public SysResult getCropType(String cropName) {
        List<String> type = cropGrowdateIndexlibService.getType(cropName);
        return SysResult.success(type);
    }

    @ApiOperation("农作物历史产量查询")
    @GetMapping("/getCropYieldHistory")
    public SysResult getCropYieldHistory(String stationId, String cropName, String type, int year1, int year2) {
        List<CropyieldHistory> cropyieldHistories = cropyieldHistoryService.listByParams(stationId, cropName, type, year1, year2);
        return SysResult.success(cropyieldHistories);
    }

    @ApiOperation("农作物预报产量查询")
    @GetMapping("/getCropYieldFcst")
    public SysResult getCropYieldFcst(String stationId, String cropName, String type, int year1, int year2) {
        List<CropyieldFcst> list = cropyieldFcstService.getList4(year1, year2, stationId, type, cropName);
        return SysResult.success(list);
    }

    @ApiOperation("农作物产量统计查询")
    @GetMapping("/getCltj")
    public SysResult getCltj(String stationId, String cropName, String type, int year1, int year2) {
        List<CltjDto> cltj = cltjService.getCltj(stationId, cropName, type, year1, year2);
        return SysResult.success(cltj);
    }

    @ApiOperation("农作物产量查询统计查询导出excel")
    @GetMapping("/getCltj/exportExcel")
    public void cltjExportExcel(String stationId, String cropName, String type, int year1, int year2, HttpServletResponse response){
        List<CltjDto> cltj = cltjService.getCltj(stationId, cropName, type, year1, year2);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("农作物产量", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //生成excel并返回
            EasyExcel.write(response.getOutputStream(), CltjDto.class).sheet("sheet1").registerWriteHandler(new CustomCellWriteWeightConfig()).doWrite(cltj);
        } catch (Exception e){
            e.printStackTrace();
            System.err.println("导出失败");
        }

    }

    @ApiOperation("获取时间段内雨量、日照、温度统计图")
    @GetMapping("/getSumRainAndSunAndTemp")
    public SysResult getSumRainAndSunAndTemp(String stationId,Integer year1,Integer month1,Integer year2,Integer month2){
        SumRainAndSunAndTempListVo sumRainAndSunAndTempList = fyqtjService.getSumRainAndSunAndTempList(stationId, year1, month1, year2, month2);
        return SysResult.success(sumRainAndSunAndTempList);
    }

    @ApiOperation("获取时间段内雨量、日期、温度统计图")
    @GetMapping("/getSumRainAndSunAndTemp/exportExcel")
    public void getSumRainAndSunAndTempExportExcel(String stationId,Integer year1,Integer month1,Integer year2,Integer month2,HttpServletResponse response){
        SumRainAndSunAndTempListVo sumRainAndSunAndTempList = fyqtjService.getSumRainAndSunAndTempList(stationId, year1, month1, year2, month2);
        List<SumDataVo> tempDataList = sumRainAndSunAndTempList.getTempData();
        List<SumDataVo> sunDataList = sumRainAndSunAndTempList.getSunData();
        List<SumDataVo> rainDataList = sumRainAndSunAndTempList.getRainData();
        List<SumRainAndSunAndTempDto> sumRainAndSunAndTempDtoList = new ArrayList<>();
        for (SumDataVo tempData : tempDataList) {
            SumRainAndSunAndTempDto sumRainAndSunAndTempDto = new SumRainAndSunAndTempDto();
            String time = tempData.getTime();
            String[] split = time.split("-");
            Integer year = Integer.parseInt(split[0]);
            Integer month = Integer.parseInt(split[1]);
            sumRainAndSunAndTempDto.setYear(year);
            sumRainAndSunAndTempDto.setMonth(month);
            sumRainAndSunAndTempDto.setTemp(tempData.getValue());
            for (SumDataVo sunData : sunDataList) {
                if (sunData.getTime().equals(tempData.getTime())){
                    sumRainAndSunAndTempDto.setSunHour(sunData.getValue());
                    break;
                }
            }
            for (SumDataVo rainData:rainDataList){
                if (rainData.getTime().equals(tempData.getTime())){
                    sumRainAndSunAndTempDto.setRain(rainData.getValue());
                    break;
                }
            }
            sumRainAndSunAndTempDtoList.add(sumRainAndSunAndTempDto);
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("平均温度、日照时数、累计雨量统计", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //生成excel并返回
            EasyExcel.write(response.getOutputStream(), SumRainAndSunAndTempDto.class).sheet("sheet1").registerWriteHandler(new CustomCellWriteWeightConfig()).doWrite(sumRainAndSunAndTempDtoList);
        } catch (Exception e){
            e.printStackTrace();
            System.err.println("导出失败");
        }
    }

    @ApiOperation("获取发育期预报列表")
    @GetMapping("/getGrowDateFcst")
    public SysResult getCrowDateFcst(String cropName,String type,String stationId,long year){
        List<CropGrowdateFcst> cropGrowdateFcstList = growdateFcstService.listByYear1(year, stationId, type, cropName);
        return SysResult.success(cropGrowdateFcstList);
    }

    @ApiOperation("获取发育期实况列表")
    @GetMapping("/getGrowDateHistory")
    public SysResult getGrowDateHistory(String cropName,String type,String stationId,long year){
        List<CropGrowdateHistory> list1 = cropGrowdateHistoryService.getList1(year, stationId, type, cropName);
        return SysResult.success(list1);
    }

    @ApiOperation("获取发育期列表")
    @GetMapping("/getGrowDateList")
    public SysResult getGrowDateList(String cropName,String type,String stationId,long year1,long year2,String growName){
        List<CropGrowdateHistory> cropGrowdateHistoryList = cropGrowdateHistoryService.getList2(year1,year2,stationId,type,cropName,growName);
        List<CropGrowdateFcst> cropGrowdateFcstList = growdateFcstService.listByYear2(year1, year2, stationId, type, cropName, growName);
        List<GrowdateListVo> growdateListVoList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd");
        for (CropGrowdateHistory cropGrowdateHistory : cropGrowdateHistoryList) {
            GrowdateListVo vo = new GrowdateListVo();
            vo.setGrowName(cropGrowdateHistory.getGrowdatename());
            vo.setHistoryDate(sdf.format(cropGrowdateHistory.getGrowdatedate()));
            vo.setHistoryYear(sdf1.format(cropGrowdateHistory.getGrowdatedate()));
            vo.setHistoryTime(sdf2.format(cropGrowdateHistory.getGrowdatedate()));
            for (CropGrowdateFcst cropGrowdateFcst : cropGrowdateFcstList) {
                if (cropGrowdateHistory.getYear() == cropGrowdateFcst.getYear() && cropGrowdateHistory.getGrowdatename().equals(cropGrowdateFcst.getGrowdatename())){
                    vo.setForecastDate(sdf.format(cropGrowdateFcst.getForecastdate()));
                    vo.setForecastYear(sdf1.format(cropGrowdateFcst.getForecastdate()));
                    vo.setForecastTime(sdf2.format(cropGrowdateFcst.getForecastdate()));
                    break;
                }
            }
            growdateListVoList.add(vo);
        }

        return SysResult.success(growdateListVoList);
    }

    @ApiOperation("获取发育期列表")
    @GetMapping("/getGrowDateList1")
    public SysResult getGrowDateList1(String cropName,String type,String stationId,long year1,long year2,String growName){
        List<CropGrowdateHistory> cropGrowdateHistoryList = cropGrowdateHistoryService.getList2(year1,year2,stationId,type,cropName,growName);
        List<CropGrowdateFcst> cropGrowdateFcstList = growdateFcstService.listByYear2(year1, year2, stationId, type, cropName, growName);
        List<GrowdateListVo> growdateListVoList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (CropGrowdateHistory cropGrowdateHistory : cropGrowdateHistoryList) {
            GrowdateListVo vo = new GrowdateListVo();
            vo.setGrowName(cropGrowdateHistory.getGrowdatename());
            vo.setHistoryDate(sdf.format(cropGrowdateHistory.getGrowdatedate()));
            for (CropGrowdateFcst cropGrowdateFcst : cropGrowdateFcstList) {
                if (cropGrowdateHistory.getYear() == cropGrowdateFcst.getYear() && cropGrowdateHistory.getGrowdatename().equals(cropGrowdateFcst.getGrowdatename())){
                    vo.setForecastDate(sdf.format(cropGrowdateFcst.getForecastdate()));
                    break;
                }
            }
            growdateListVoList.add(vo);
        }

        return SysResult.success(growdateListVoList);
    }

    @ApiOperation("获取发育期列表导出excel")
    @GetMapping("/getGrowDateList/exportExcel")
    public void growDateListExportExcel(String cropName,String type,String stationId,long year1,long year2,String growName,HttpServletResponse response){
        List<CropGrowdateHistory> cropGrowdateHistoryList = cropGrowdateHistoryService.getList2(year1,year2,stationId,type,cropName,growName);
        List<CropGrowdateFcst> cropGrowdateFcstList = growdateFcstService.listByYear2(year1, year2, stationId, type, cropName, growName);
        List<GrowdateListVo> growdateListVoList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (CropGrowdateHistory cropGrowdateHistory : cropGrowdateHistoryList) {
            GrowdateListVo vo = new GrowdateListVo();
            vo.setGrowName(cropGrowdateHistory.getGrowdatename());
            vo.setHistoryDate(sdf.format(cropGrowdateHistory.getGrowdatedate()));
            for (CropGrowdateFcst cropGrowdateFcst : cropGrowdateFcstList) {
                if (cropGrowdateHistory.getYear() == cropGrowdateFcst.getYear() && cropGrowdateHistory.getGrowdatename().equals(cropGrowdateFcst.getGrowdatename())){
                    vo.setForecastDate(sdf.format(cropGrowdateFcst.getForecastdate()));
                    break;
                }
            }
            growdateListVoList.add(vo);
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("农作物发育期", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //生成excel并返回
            EasyExcel.write(response.getOutputStream(), GrowdateListVo.class).sheet("sheet1").registerWriteHandler(new CustomCellWriteWeightConfig()).doWrite(growdateListVoList);
        } catch (Exception e){
            e.printStackTrace();
            System.err.println("导出失败");
        }
    }

    @ApiOperation("获取作物名称-作物发育期指标库")
    @GetMapping("/getGrowCropName")
    public SysResult getGrowCropName() {
        List<String> cropName = growdateIndexlibService.getCropName();
        return SysResult.success(cropName);
    }

    @ApiOperation("获取发育期名称")
    @GetMapping("/getMoniGrowDateName")
    public SysResult getMoniGrowDateName(String cropName) {
        List<String> growDateName = growdateIndexlibService.getGrowDateName(cropName);
        return SysResult.success(growDateName);
    }

    @ApiOperation("获取农作物监控信息")
    @GetMapping("/getAgriMoniInfo")
    public SysResult getAgriMoniInfo(String stationId, String warningTime1, String warningTime2, String cropName, String growdateName) {
        List<AgriMoniInfo> agriMoniInfoList = agriMoniInfoService.listByParam1(stationId, warningTime1, warningTime2,cropName,growdateName);
        agriMoniInfoList = agriMoniInfoList.stream().map(i -> {
            AgriMoniInfo bo = new AgriMoniInfo();
            BeanUtils.copyProperties(i, bo);
            bo.setCropname(bo.getCropname().trim());
            bo.setGrowdatename(bo.getGrowdatename().trim());
            bo.setWarningtype(bo.getWarningtype().trim());
            return bo;
        }).collect(Collectors.toList());
        return SysResult.success(agriMoniInfoList);
    }


}
